/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.userinfo.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.icanci.basic.commonutils.R;
import cn.icanci.basic.exception.ApplicationException;
import cn.icanci.userinfo.client.BaseDataServiceClient;
import cn.icanci.userinfo.entity.EmailDataVO;
import cn.icanci.userinfo.entity.UserInfo;
import cn.icanci.userinfo.entity.UserRegisterVO;
import cn.icanci.userinfo.service.UserInfoService;
import cn.icanci.userinfo.utils.Convert;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.*;

import com.alibaba.nacos.client.naming.utils.StringUtils;

/**
 * @author icanci
 * @date Created in 2021/04/10 22:05
 * @version 1.0
 */
@SuppressWarnings("all")
@RestController
@Slf4j
@RequestMapping("/userInfo")
public class UserInfoController extends BaseController {

    @Resource
    private BaseDataServiceClient baseDataServiceClient;
    @Resource
    private UserInfoService       userInfoService;

    // ================ 下面的只是用户账号密码登录注册 ================
    @PostMapping("/register")
    public R register(@RequestBody UserRegisterVO userInfoVO) {
        tradeLogService.setLogInfo("USER_INFO", "REGISTER", "");
        try {
            String code = baseDataServiceClient.getCode(userInfoVO.getPhoneNumber());
            if (StringUtils.isEmpty(code) || !code.equals(userInfoVO.getCode())) {
                return R.error().message("请输入正确的验证码");
            }
            UserInfo userInfo = Convert.userRegisterVO2UserInfo(userInfoVO);
            // 先进行查询
            UserInfo temp = userInfoService.queryOneRowByPhone(userInfo);
            if (null == temp) {
                // 日志统计注册的信息个数
                tradeLogService.info(log, "用户注册，注册账号信息为:{}", userInfo.getPhoneNumber());
                userInfoService.insertOneRow(userInfo);
                return R.ok().data("userInfo", userInfo);
            }
            return R.error().message("此用户已经注册过，请登录");
        } catch (ApplicationException e) {
            return R.error().message(e.getMsg());
        } finally {
            tradeLogService.removeAll();
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody UserInfo userInfo) {
        tradeLogService.setLogInfo("USER_INFO", "LOGIN", "");
        try {
            tradeLogService.info(log, "用户登录，登录账号信息为:{}", userInfo.getPhoneNumber());
            // 先进行查询
            UserInfo temp = userInfoService.queryOneRow(userInfo);
            if (null == temp) {
                return R.error().message("账号或者密码错误");
            }
            return R.ok().message("登录成功").data("userInfo", temp);
        } catch (ApplicationException e) {
            return R.error().message(e.getMsg());
        } finally {
            tradeLogService.removeAll();
        }
    }

    @PostMapping("/getBaseData")
    public R getBaseData(@RequestBody UserInfo userInfo) {
        tradeLogService.setLogInfo("USER_INFO", "GET_BASE_DATA", "");
        try {
            tradeLogService.info(log, "用户查询，查询账号信息为:{}", userInfo.getPhoneNumber());
            // 先进行查询
            UserInfo temp = userInfoService.queryOneRowByPhone(userInfo);
            if (null == temp) {
                return R.error().message("账号或者密码错误");
            }
            return R.ok().message("查询成功").data("userInfo", temp);
        } catch (ApplicationException e) {
            return R.error().message(e.getMsg());
        } finally {
            tradeLogService.removeAll();
        }
    }

    @PostMapping("/update")
    public R updateUserInfo(@RequestBody UserInfo userInfo) {
        tradeLogService.setLogInfo("USER_INFO", "UPDATE", "");
        try {
            tradeLogService.info(log, "用户更新信息，更新账号信息为:{}", userInfo.getPhoneNumber());
            userInfoService.updateOneRow(userInfo);
            UserInfo temp = userInfoService.queryOneRowByPhone(userInfo);
            return R.ok().message("修改成功").data("userInfo", temp);
        } catch (ApplicationException e) {
            return R.error().message(e.getMsg());
        } finally {
            tradeLogService.removeAll();
        }
    }

    @PostMapping("/updateEmail")
    public R updateUserInfoEmail(@RequestBody EmailDataVO emailDataVO) {
        tradeLogService.setLogInfo("USER_INFO", "UPDATE_BY_EMAIL", "");
        // 验证验证码
        String code = baseDataServiceClient.getCode(emailDataVO.getEmailAddress());
        if (StringUtils.isEmpty(code) || !code.equals(emailDataVO.getCode())) {
            return R.error().message("请输入正确的验证码");
        }
        // 数据转换
        UserInfo userInfo = new UserInfo();
        userInfo.setEmailAddress(emailDataVO.getEmailAddress());
        userInfo.setPhoneNumber(emailDataVO.getPhoneNumber());
        try {
            tradeLogService.info(log, "用户更新信息，更新账号信息为:{}", userInfo.getPhoneNumber());
            userInfoService.updateOneRow(userInfo);
            UserInfo temp = userInfoService.queryOneRowByPhone(userInfo);
            return R.ok().message("修改成功").data("userInfo", temp);
        } catch (ApplicationException e) {
            return R.error().message(e.getMsg());
        } finally {
            tradeLogService.removeAll();
        }
    }

    //  ================ 用户账号验证码 ================
    @PostMapping("/codeLogin")
    public R codeLogin(@RequestBody UserRegisterVO userInfoVO) {
        try {
            tradeLogService.setLogInfo("USER_INFO", "CODE_LOGIN", "");
            tradeLogService.info(log, "用户使用验证码登录，用户信息:{}", userInfoVO.getPhoneNumber());
            String code = baseDataServiceClient.getCode(userInfoVO.getPhoneNumber());
            if (StringUtils.isEmpty(code) || !code.equals(userInfoVO.getCode())) {
                return R.error().message("验证码错误");
            }
            UserInfo userInfo = Convert.userRegisterVO2UserInfo(userInfoVO);
            UserInfo result = userInfoService.queryOneRowByPhone(userInfo);
            return R.ok().data("userInfo", result);
        } finally {
            tradeLogService.removeAll();
        }
    }

    @GetMapping("/queryAllUserInfo")
    public R queryAllUserInfo() {
        try {
            tradeLogService.setLogInfo("USER_INFO", "QUERY_ALL_USER_INFO", "");
            tradeLogService.info(log, "管理员查询用户信息");
            List<UserInfo> userInfos = userInfoService.queryAllUserInfo();
            if (CollectionUtil.isEmpty(userInfos)) {
                tradeLogService.warn(log, "暂时无用户信息");
                return R.error().message("暂时无用户信息");
            }
            tradeLogService.info(log, "查询成功,数量：{}", userInfos.size());
            return R.ok().message("查询成功～").data("userInfos", userInfos);
        } finally {
            tradeLogService.removeAll();
        }
    }
    @GetMapping("/queryOneUserInfo/{id}")
    public R queryOneUserInfo(@PathVariable("id") Integer id) {
        try {
            tradeLogService.setLogInfo("USER_INFO", "QUERY_ONE_USER_INFO", "");
            tradeLogService.info(log, "订单接口查询用户信息");
            UserInfo userInfo = userInfoService.queryOneUserInfo(id);
            if (null == userInfo) {
                tradeLogService.warn(log, "暂时无用户信息");
                return R.error().message("暂时无用户信息");
            }
            tradeLogService.info(log, "查询成功,userInfo：{}", userInfo);
            return R.ok().message("查询成功～").data("userInfo", userInfo);
        } finally {
            tradeLogService.removeAll();
        }
    }
}
